var map = null;
var appD;
var extent = [0, 0, 1024, 400];//图片图层四至
var projection = new ol.proj.Projection({//定义坐标系
    code: 'xkcd-image',
    units: 'pixels',
    extent: extent
});
//标记图层
var layerPop;
//信息弹框
var popup;
//闪烁图层
var point_overlay;

var mapLayer;

var userPop;

var helper = {
    init: function (id, url) {
        jsHelper.initMap(url);
        jsHelper.move();
        jsHelper.initLocator(id);
        jsHelper.showPhop();
        jsHelper.addLayer();
    },
    initIndeMap: function (id, url) {
        jsHelper.initMap(url);
        jsHelper.initLocator(id);
        jsHelper.showPhop();
        map.removeInteraction(appD);
    },

    initTrack: function (param) {
        mapList = param;
        mapIndex = 0;
        helper.showTrack(mapList[mapIndex]);
    },

    showTrack: function (item) {
        index = 0;
        date = 0;
        tempDate = 0;
        $("#strId").val(item.strId);
        $("#strName").text(item.strName);
        $("#strName").val(item.strName);
        var url = encodeURI(item.imgUrl);
        //处理坐标
        trackHelper.dealPoints(item.points);
        //初始化地图
        jsHelper.initMap(url);
        if (trackLayer != null) {
            map.removeLayer(trackLayer);
            map.removeLayer(speedLayer);
        }
        trackLayer = new ol.layer.Vector({
            source: new ol.source.Vector(),
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'rgba(255, 0, 0, 0.5)'
                }),
                stroke: new ol.style.Stroke({
                    color: 'red',
                    width: 1
                })
            })
        });
        speedLayer = new ol.layer.Vector({
            source: new ol.source.Vector()
        });
        map.addLayer(trackLayer);
        map.addLayer(speedLayer);
        trackHelper.addPolygon();
        $("#tempstop").unbind("click");
        $("#tempstop").click(function () {
            map.render();
            clearInterval(inter);
            if (date != 0) {
                tempDate = (new Date()).getTime();
            }
            ispuse = 1;
        });
        $("#start").unbind("click");
        $("#start").click(function () {
            if (date == 0) {
                date = (new Date()).getTime();
            }
            if (tempDate != 0) {
                date = date + ((new Date()).getTime() - tempDate);
            }
            ispuse = 0;
            trackHelper.startAnimation();
            trackHelper.startMove();
        });
        $("#stop").unbind("click");
        $("#stop").click(function () {
            trackHelper.stopAnimation();
            clearInterval(inter);
        });
        $("#next").unbind("click");
        $("#next").click(function () {
            index = index + 1;
            date = date - speed;
            map.render();
        });
        $("#prev").unbind("click");
        $("#prev").click(function () {
            index = index - 1;
            date = date + speed;
            map.render();
        });
        //自动点击开始按钮
        if (document.all) {
            document.getElementById("start").click();
        }
        // 其它浏览器
        else {
            var e = document.createEvent("MouseEvents");
            e.initEvent("click", true, true);
            document.getElementById("start").dispatchEvent(e);
        }
    }
};

var jsHelper = {
    //初始化地图
    initMap: function (url) {
        if (map == null) {
            map = new ol.Map({
                target: 'map',
                view: new ol.View({
                    projection: projection,
                    center: ol.extent.getCenter(extent),
                    zoom: 2,
                    minZoom: 2,
                    maxZoom: 4
                }),
                interactions: ol.interaction.defaults({
                    pinchRotate: false,
                    doubleClickZoom: false
                })

            });
            map.addControl(new ol.control.ZoomToExtent());
        } else {
            map.removeLayer(mapLayer);
            map.removeLayer(layerPop);
            map.getLayers().forEach(function (value) {
                map.removeLayer(value);
            });
        }
        //如果有闪烁图层，直接移除
        if (point_overlay != null) {
            map.removeOverlay(point_overlay);
        }
        if (popup != null) {
            var element = popup.getElement();
            $(element).popover('destroy');
        }
        //设备图层
        layerPop = new ol.layer.Vector({
            source: new ol.source.Vector()
        });
        mapLayer = new ol.layer.Image({
            source: new ol.source.ImageStatic({
                url: url,//地址
                projection: projection,
                imageExtent: extent
            })
        });
        map.addLayer(mapLayer);
        map.addLayer(layerPop);
    },
    //初始化地图上的标注
    initLocator: function (strId) {
        var requestData = {
            strId: strId,
            show: true
        };
        $.ajax({
            url: "/equipment/locator/strId",//请求路径
            type: "post",//请求方式
            data: requestData,//请求参数
            success: function (apiResult) {
                if (apiResult.resultCode === 2000) {
                    $.each(apiResult.data, function (index, item) {
                        jsHelper.showAnchor(item)
                    })
                }
            }, error: function () {

            },
            dataType: "json" //服务器响应的数据格式

        })
    },
    //展示图标
    showAnchor: function (item) {
        var x = item.locatorInfo.longitude - 0;
        var y = item.locatorInfo.latitude - 0;
        var anchor = new ol.Feature({
            geometry: new ol.geom.Point([x, y])
        });
        // 设置样式,不同设备类型用不同的icon，在样式中就可以设置图标
        var iconPath = path + '/resource/map/icon/icon.jpg';
        if (item.typeCode == 2 || item.typeCode == 3) {
            iconPath = path + '/resource/map/icon/icon2.png';
        }
        anchor.setStyle(new ol.style.Style({
            image: new ol.style.Icon({
                src: iconPath,
                anchor: [0.5, 0.5],
                crossOrigin: 'anonymous',
                size: [30, 30]
            }),

        }));
        anchor.setId(item.no);
        anchor.setProperties({
            no: item.no,
            version: item.version,
            typeDesc: item.typeDesc,
            voltageStatus: item.voltageStatus,
            status: item.status ? "报警" : "未报警",
            dismantleStatus: item.dismantleStatus ? "正常" : "异常",
            onlineStatus: item.onlineStatus ? "在线" : "离线",
            desc: item.desc == null ? "" : item.desc
        });
        // 添加到之前的创建的layer中去
        layerPop.getSource().addFeature(anchor);
    },
    //展示图标的详细信息
    showPhop: function () {
        popup = new ol.Overlay({
            element: document.getElementById('popup'),
            //是否自动平移，即假如标记在屏幕边缘，弹出时自动平移地图使弹出框完全可见
            autoPan: true
        });
        map.addOverlay(popup);
        popup.setPositioning("bottom-center");
        map.on('click', function (evt) {
            var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
                return feature;
            });
            if (feature) {
                var attr = feature.getProperties();
                var content;
                if (attr.type == -1) {
                    content = '<p>隐藏点信息：</p>' +
                        '<code>隐藏点编号：' + attr.id + '</code><br>' +
                        '<code>起点设备编号：' + attr.startPoint + '</code><br>' +
                        '<code>终点设备编号：' + attr.endPoint + '</code><br>';
                    if (attr.lastPoint != '' && attr.lastPoint != null) {
                        content += '<code>上一个隐藏点编号：' + attr.lastPoint + '</code><br>';
                    }
                    if (attr.nextPoint != '' && attr.nextPoint != null) {
                        content += '<code>下一个隐藏点编号：' + attr.nextPoint + '</code><br>';
                    }
                    content += '<code style="float: right"><button onclick="addConcealPointHelper.deleteConcealPoint(' + attr.id + ')">删除</button></code>';
                } else if (attr.type == -2) {
                    content = '<p>用户信息：</p>'
                        + '<code>用户名称：' + attr.realName + '</code><br>'
                        + '<code>用户卡号：' + attr.cardId + '</code><br>'
                        + '<code>用户房间：' + attr.roomName + '</code><br>';
                    // + '<code>定位时间：' + attr.createTime + '</code><br>';

                } else {
                    content = '<p>设备信息：</p>' +
                        '<code>设备名称：' + attr.no + '</code><br>' +
                        '<code>设备版本：' + attr.version + '</code><br>' +
                        '<code>设备类型：' + attr.typeDesc + '</code><br>';
                    if (attr.desc != '') {
                        content += '<code>设备描述：' + attr.desc + '</code><br>';
                    }
                }
                var element = popup.getElement();
                var coordinate = evt.coordinate;
                $(element).popover('destroy');
                popup.setPosition(coordinate);
                $(element).popover({
                    placement: 'top',
                    animation: false,
                    html: true,
                    content: content
                });
                $(element).popover('show');
            } else {
                var element = popup.getElement();
                $(element).popover('destroy');
            }

        });
    },
    //显示用户位置
    showUser: function (item) {
        var x = item.longitude - 0 + jsHelper.random();
        var y = item.latitude - 0 + jsHelper.random();
        var anchor = new ol.Feature({
            geometry: new ol.geom.Point([x, y])
        });
        // 不同类型的用户展示不同的图片
        var iconPath = path + '/resource/map/icon/user2.png';
        if (item.userType == "WORKER") {
            iconPath = path + '/resource/map/icon/admin.png';
        }
        anchor.setStyle(new ol.style.Style({
            image: new ol.style.Icon({
                src: iconPath,
                anchor: [0.5, 0.5],
                crossOrigin: 'anonymous',
                size: [30, 30]
            }),

        }))
        anchor.setId(item.no);
        anchor.setProperties({
            cardId: item.cardId,
            realName: item.realName,
            createTime: item.createTime,
            roomName:item.roomName,
            type: -2,
        });
        // 添加到之前的创建的layer中去
        userPop.getSource().addFeature(anchor);
    },
    random: function () {
        var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
        var num = Math.random() * 5 * plusOrMinus;
        return num;
    },
    //拖动图标
    move: function () {
        var app = {};
        /**
         * @constructor
         * @extends {ol.interaction.Pointer}
         */
        app.Drag = function () {
            ol.interaction.Pointer.call(this, {
                handleDownEvent: app.Drag.prototype.handleDownEvent,
                handleDragEvent: app.Drag.prototype.handleDragEvent,
                handleMoveEvent: app.Drag.prototype.handleMoveEvent,
                handleUpEvent: app.Drag.prototype.handleUpEvent
            });
            this.coordinate_ = null;
            this.cursor_ = 'pointer';
            this.feature_ = null;
            this.previousCursor_ = undefined;

        };
        ol.inherits(app.Drag, ol.interaction.Pointer);
        app.Drag.prototype.handleDownEvent = function (evt) {
            var map = evt.map;
            var feature = map.forEachFeatureAtPixel(evt.pixel,
                function (feature) {
                    return feature;
                });
            if (feature) {
                this.coordinate_ = evt.coordinate;
                this.feature_ = feature;
            }

            return !!feature;
        };
        app.Drag.prototype.handleDragEvent = function (evt) {
            var deltaX = evt.coordinate[0] - this.coordinate_[0];
            var deltaY = evt.coordinate[1] - this.coordinate_[1];

            var geometry = this.feature_.getGeometry();
            geometry.translate(deltaX, deltaY);
            this.coordinate_[0] = evt.coordinate[0];
            this.coordinate_[1] = evt.coordinate[1];
            //console.log(this);
        };
        app.Drag.prototype.handleMoveEvent = function (evt) {
            if (this.cursor_) {
                var map = evt.map;
                var feature = map.forEachFeatureAtPixel(evt.pixel,
                    function (feature) {
                        return feature;
                    });
                var element = evt.map.getTargetElement();
                if (feature) {
                    if (element.style.cursor != this.cursor_) {
                        this.previousCursor_ = element.style.cursor;
                        element.style.cursor = this.cursor_;
                    }
                } else if (this.previousCursor_ !== undefined) {
                    element.style.cursor = this.previousCursor_;
                    this.previousCursor_ = undefined;
                }
            }
        };
        app.Drag.prototype.handleUpEvent = function () {
            var address = $("#strName").val();
            if (this.feature_.get("type") == -1) {
                var requestData = {
                    id: this.feature_.get("id"),
                    longitude: this.coordinate_[0],
                    latitude: this.coordinate_[1],
                };
                $.ajax({
                    url: "/equipment/update/conceal/point",//请求路径

                    type: "post",//请求方式
                    data: requestData,//请求参数
                    success: function (apiResult) {
                    }, error: function () {

                    },
                    dataType: "json" //服务器响应的数据格式

                });
            } else {
                var requestData = {
                    no: this.feature_.get("no"),
                    structureId: $("#strId").val(),
                    longitude: this.coordinate_[0],
                    latitude: this.coordinate_[1],
                    address: address
                };
                $.ajax({
                    url: "/equipment/save/location",//请求路径
                    type: "post",//请求方式
                    data: requestData,//请求参数
                    success: function (apiResult) {
                    }, error: function () {

                    },
                    dataType: "json" //服务器响应的数据格式

                });
            }
            this.coordinate_ = null;
            this.feature_ = null;
            return false;
        };
        appD = new app.Drag();
        map.addInteraction(appD);
    },
    //添加图标
    addLayer: function () {
        map.on('click', function (evt) {
            var no = $("#selectNo").val();
            var address = $("#strName").val();
            if (no != null && no != "") {
                //保存位置
                var requestData = {
                    no: no,
                    structureId: $("#strId").val(),
                    longitude: evt.coordinate[0],
                    latitude: evt.coordinate[1],
                    address: address
                };
                $.ajax({
                    url: "/equipment/save/location",//请求路径
                    type: "post",//请求方式
                    data: requestData,//请求参数
                    success: function (apiResult) {
                        //如果保存成功，添加图层
                        jsHelper.showAnchor(apiResult.data);
                        //将selectNo至空
                        $("#selectNo").val("");
                        //将对应的地址直接修改
                        $("#" + no + "_address").text(address);
                        //将图片变回鼠标
                        var url = encodeURI(path + "/resource/img/a1.jpg");
                        document.body.style.cursor = "url(" + url + ") 12 12,default";

                    }, error: function () {

                    },
                    dataType: "json" //服务器响应的数据格式
                });
            }
        });

    },
    //闪烁图层,以及点击闪烁图层展示报警人信息
    pointDiv: function (item, type) {
        var point_div = document.createElement('div');
        //普通定位
        if (type == 1) {
            point_div.className = "css_animation_location";
        } else {
            point_div.className = "css_animation";
        }
        map.removeOverlay(point_overlay);
        point_overlay = new ol.Overlay({
            element: point_div,
            positioning: 'center-center'
        });
        map.addOverlay(point_overlay);
        point_overlay.setPosition([item.longitude, item.latitude]);

        point_div.onclick = function () {
            //显示报警人信息
            popup = new ol.Overlay({
                element: document.getElementById('popup'),
                //是否自动平移，即假如标记在屏幕边缘，弹出时自动平移地图使弹出框完全可见
                autoPan: true
            });
            map.addOverlay(popup);
            popup.setPositioning("bottom-center");
            var element = popup.getElement();
            var content = '<p>用户信息：</p>'
                + '<code>用户名称：' + item.realName + '</code><br>'
                + '<code>用户卡号：' + item.cardId + '</code><br>'
                + '<code>用户房间：' + item.roomName + '</code><br>';
            // + '<code>定位时间：' + item.createTime + '</code><br>';
            $(element).popover('destroy');
            popup.setPosition(point_overlay.getPosition());
            $(element).popover({
                placement: 'top',
                animation: false,
                html: true,
                content: content
            });
            $(element).popover('show');
        }
    }

};


/********************************************************************轨迹相关*********************************************************/

//轨迹图层
var trackLayer;
//动画图层
var speedLayer;
//样式
var style = new ol.style.Style({
    image: new ol.style.Circle({
        radius: 5,
        snapToPixel: false,
        fill: new ol.style.Fill({color: 'rgba(30,144,255,1)'}),
        stroke: new ol.style.Stroke({
            color: 'rgb(30,144,255)', width: 2
        })
    })
});
//速度
var speed = 100;
//轨迹开始标记
var geoMarker;
//轨迹结束标记
var endMarker;
//动画相关参数
var index = 0;
var date = 0;
var tempDate = 0;
var inter;
var ispuse = 0;
var newPoints = [];

var mapIndex = 0;
var mapList;
var trackHelper = {
    //点位处理
    dealPoints: function (points) {
        newPoints = [];
        $.each(points, function (i, item) {
            var currLng = parseFloat(item[0]);
            var currLat = parseFloat(item[1]);

            newPoints.push(ol.proj.fromLonLat([currLng, currLat], projection));

            if ((i + 1) == points.length) {
                return false;
            }

            var nextLng = parseFloat(points[i + 1][0]);
            var nextLat = parseFloat(points[i + 1][1]);

            var diffLng = nextLng - currLng;
            var diffLat = nextLat - currLat;

            var currParamsLng = 0;
            var currParamsLat = 0;

            var base = 1;

            currParamsLng = base;
            currParamsLat = (diffLat / diffLng) * base;

            if (diffLng < diffLat) {
                currParamsLng = (diffLng / diffLat) * base;
                currParamsLat = base
            }
            if (currParamsLng < 0) {
                currParamsLng = -currParamsLng;
            }

            if (diffLat > 0) {
                if (currParamsLat < 0) {
                    currParamsLat = -currParamsLat;
                }
            } else {
                if (currParamsLat > 0) {
                    currParamsLat = -currParamsLat;
                }
            }

            if (diffLng == 0) {
                currParamsLng = 0;
                currParamsLat = base;
            }

            if (diffLat == 0) {
                currParamsLng = base;
                currParamsLat = 0;
            }

            if (diffLng > 0) {
                currLng = currLng + currParamsLng;
                currLat = currLat + currParamsLat;
                while (currLng < nextLng) {

                    newPoints.push(ol.proj.fromLonLat([currLng, currLat], projection));

                    currLng = currLng + currParamsLng;
                    currLat = currLat + currParamsLat;
                }
            } else if (diffLng < 0) {
                currLng = currLng - currParamsLng;
                currLat = currLat + currParamsLat;
                while (currLng > nextLng) {

                    newPoints.push(ol.proj.fromLonLat([currLng, currLat], projection));
                    currLng = currLng - currParamsLng;
                    currLat = currLat + currParamsLat;
                }
            } else {
                currLng = currLng + currParamsLng;
                currLat = currLat + currParamsLat;
                while (currLat < nextLat) {

                    newPoints.push(ol.proj.fromLonLat([currLng, currLat], projection));
                    currLng = currLng + currParamsLng;
                    currLat = currLat + currParamsLat;
                }
            }
        });
    },

    //画出轨迹
    addPolygon: function () {
        trackLayer.getSource().clear();
        var line = new ol.geom.LineString(newPoints);
        var feature = new ol.Feature({
            geometry: line
        });
        trackLayer.getSource().addFeature(feature);
        trackHelper.setMoveMark();
    },

    //添加开始结束点位
    setMoveMark: function () {
        geoMarker = new ol.Feature({
            geometry: new ol.geom.Point(newPoints[0])
        });
        geoMarker.setStyle(style);
        endMarker = new ol.Feature({
            geometry: new ol.geom.Point(newPoints[newPoints.length - 1])
        });
    },

    moveFeature: function (event) {
        var vectorContext = event.vectorContext;
        //
        if (index >= newPoints.length) {
            trackHelper.stopAnimation();
            //调用下一个次方法
            mapIndex = mapIndex + 1;
            if (mapIndex < mapList.length) {
                helper.showTrack(mapList[mapIndex]);
            }
            return;
        }

        var currentPoint = new ol.geom.Point(newPoints[index]);
        var feature = new ol.Feature(currentPoint);
        vectorContext.drawFeature(feature, style);
        var frameState = event.frameState;
        if (ispuse == 0) {
            var t = frameState.time - date;
            if (t / speed > index) {
                index = index + 1;
                if (index == newPoints.length && mapIndex == mapList.length - 1) {
                    endMarker = new ol.Feature({
                        geometry: new ol.geom.Point(newPoints[newPoints.length - 1])
                    });
                    endMarker.setStyle(style);
                    speedLayer.getSource().addFeature(endMarker);
                }
            }
        }
    },
    startAnimation: function () {
        if (mapIndex == mapList.length) {
            mapIndex = 0;
            helper.showTrack(mapList[0]);
        }
        geoMarker.setStyle(style);
        map.on('postcompose', trackHelper.moveFeature);
        map.render();
    },
    stopAnimation: function () {
        index = 0;
        date = 0;
        tempDate = 0;
        (geoMarker.getGeometry()).setCoordinates(newPoints[0]);
        map.un('postcompose', trackHelper.moveFeature);
    },
    startMove: function () {
        inter = setInterval(function () {
            map.render();
        }, speed);
    }
};
